<template>
  <div class="app-container home">
    <el-row :gutter="10">
      <!--表定义-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="输入表定义标题"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-menu :collapse="false" class="el-menu-vertical-demo">
            <div v-if="!formDefList || formDefList.length<=0" style="padding: 20px; text-align: center; color: #bababa;">无数据</div>
            <el-menu-item :index="formDef.formKey" v-for="(formDef) in formDefList" @click="openTab(formDef)">
              <i class="el-icon-menu1"></i>
              <span slot="title">{{formDef.formTitle+'（'+formDef.id+'）'}}</span>
            </el-menu-item>
          </el-menu>
        </div>
      </el-col>
      <!--表数据-->
      <el-col :span="20" :xs="24">
        <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">
          <div v-if="!editableTabs || editableTabs.length<=0" style="padding: 80px; text-align: center; color: #bababa; font-size: 24px;">请选择数据表进行查询</div>
          <el-tab-pane
            v-for="(item, index) in editableTabs"
            :key="item.id"
            :label="item.formTitle+'（'+item.id+'）'"
            :name="item.id"
          >
            <div>
              <el-input v-model="item.queryParams.keyword"
                        placeholder="请输入关键字"
                        clearable
                        size="small"
                        style="width: 240px; margin-right: 10px;"
                        @keyup.enter.native="getList(item)"
              />
              <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery(item)">搜索</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd(item)">新增数据</el-button>
            </div>

            <el-table v-loading="loading" :data="item.dataList">
              <el-table-column label="数据id" width="240" align="left" prop="_meta.dataId"/>
              <el-table-column label="版本" width="80" align="left" prop="_meta.dataVersion">
                <template slot-scope="scope">
                  <router-link :to="'/openform/dataHisList/'+scope.row._meta.formDefKey+'/'+scope.row._meta.dataId" class="link-type">
                    <span>{{ scope.row._meta.dataVersion }}</span>
                  </router-link>
                </template>
              </el-table-column>

              <el-table-column :label="col.columnTitle" align="left" :prop="col.columnName" width="180"
                               v-for="(col, index) in item.columns" v-if="index<3">
                <template slot-scope="scope">
                  <div v-html="'<span>'+scope.row[col.columnName]+'</span>'"></div>
                </template>
              </el-table-column>

              <el-table-column label="创建时间" align="left" prop="_meta.createTime" width="150">
                <template slot-scope="scope">
                  {{parseTime(new Date(scope.row["_meta"].createTime))}}
                </template>
              </el-table-column>
              <el-table-column label="创建人" align="left" prop="_meta.userName" width="120"/>
              <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-warning-outline"
                    @click="handleView(item.id, scope.row)"
                  >详情</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleViewJson(scope.row)"
                  >查看json</el-button>
                  <el-dropdown style="margin-left: 10px;">
                    <el-button type="text" size="mini">
                      更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="handleDelete(item.formKey, scope.row)" divided icon="el-icon-delete">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="item.total>0"
              :total="item.total"
              :page.sync="item.queryParams.pageNum"
              :limit.sync="item.queryParams.pageSize"
              @pagination="getList(item)"
            />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 测试运行的返回结果 -->
    <el-dialog :visible.sync="runDialog.open" :title="runDialog.title" width="40%">
      <pre>{{ JSON.stringify(runDialog.json, null, 4) }}</pre>
      <span slot="footer" class="dialog-footer">
        <el-button @click="runDialog.open = false">关闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
    import {getDef, listDef} from "@/api/openform/generator";
    import {removeData, searchData} from "@/api/openform/formdata";

    export default {
        name: "FormDataList",
        data() {
            return {
                runDialog: {//测试运行弹出框
                    open: false
                    , title: "数据预览"
                    , json: "{}"
                },
                deptName: null,
                loading: false,// 遮罩层
                formDefList: [],
                editableTabsValue: null,// 激活的tab
                selectedTab: null,
                editableTabs: [],//tab列表
            };
        },
        mounted() {
            listDef({}).then(response => {
                if(!response.rows) {
                    this.msgError("无可用表定义");
                    return;
                }
                this.formDefList = response.rows;
            });
        },
        created() {
        },
        methods: {
            // 查询数据
            getList(tab) {
                this.loading = true;
                searchData(tab.formKey, tab.queryParams.keyword).then(response => {
                    tab.dataList = response.rows;
                    tab.total = response.total;
                    this.loading = false;
                });
            },
            /** 搜索按钮操作 */
            handleQuery(tab) {
                tab.queryParams.pageNum = 1;
                this.getList(tab);
            },
            /** 跳转页面 */
            handleView(formId, row) {
                this.$router.push({ path: "/openform/view/"+formId+"/"+row["_meta"].dataId });
            },
            /** 跳转页面 */
            handleAdd(row) {
                this.$router.push({ path: "/openform/view/"+row.id });
            },
            openTab(formDef) {
                if(!this.inEditableTabs(formDef)) {
                    getDef(formDef.id).then((res)=> {//查询表定义详情
                        formDef = res.data;
                        formDef.queryParams = {// 初始化查询参数
                            formKey: formDef.formKey,
                            pageNum: 1,
                            pageSize: 10,
                            keyword: null
                        };
                        formDef.total = 0;
                        formDef.dataList = [];
                        this.editableTabs.push(formDef);//添加到列表
                        this.selectTab(formDef.id);
                        this.getList(this.selectedTab);
                    });
                }else {
                    this.selectTab(formDef.id);//选中
                }
            },
            inEditableTabs(formDef) {
                let found = false;
                if(this.editableTabs) {
                    for(let i in this.editableTabs) {
                        if(found = (this.editableTabs[i].id==formDef.id)) {
                            break;
                        }
                    }
                }
                return found;
            },
            selectTab(id) {
                if(this.editableTabs) {
                    for(let i in this.editableTabs) {
                        if(this.editableTabs[i].id==id) {
                            this.selectedTab = this.editableTabs[i];
                            this.editableTabsValue = this.editableTabs[i].id;
                        }
                    }
                }
            },
            removeTab(targetName) {
                let tabs = this.editableTabs;
                let activeName = this.editableTabsValue;
                let activeTab = this.selectedTab;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.id === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.id;
                                activeTab = nextTab;
                            }
                        }
                    });
                }
                this.editableTabsValue = activeName;
                this.selectedTab = activeTab;
                this.editableTabs = tabs.filter(tab => tab.id !== targetName);
            },
            handleViewJson(data) {
                this.runDialog.json = data;
                this.runDialog.open = true;
            },
            /** 删除按钮操作 */
            handleDelete(formKey, row) {
                const dataId = row['_meta'].dataId || this.ids;
                this.$confirm('确认删除数据?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return removeData(formKey, dataId);
                }).then(() => {
                    this.getList(this.selectedTab);
                    this.msgSuccess("删除成功");
                })
            },
        }
    };
</script>
<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    min-height: 500px;
  }
</style>
